const app = require('http').createServer()
const io = require('socket.io')(app);
const fs = require('fs');
var count = 0;
app.listen(4000);
var names = [];
console.log(names[count])
// function handler (req, res) {
//   fs.readFile(__dirname + '/index.html',
//   (err, data) => {
//     if (err) {
//       res.writeHead(500);
//       return res.end('Error loading index.html');
//     }

//     res.writeHead(200);
//     res.end(data);
//   });
// }

io.on('error', (socket) => {
    console.log("出现异常");
});


io.on('connection', (socket) => {
    console.log("有用户连接了");
    var time = new Date().toLocaleTimeString();
    //接受js发来的账号密码
    socket.on('user',data => {
      //oname的值判断用户名是否和现有的重复
      let oname = names.find(function(item){
        return item.name === data.name;
      });
      if(oname){ 
        console.log("重复咯")
        //如果重复,注册loginErr事件,并返回true
        socket.emit('loginErr', true);
      }else {
        count++;
        //如果不重复,注册loginErr事件,并返回false + 执行以下代码
        socket.emit('loginErr', false);
            socket.broadcast.emit('msg',{
              number: count
            });
        //对所有用户浏览器广播这个新用户
        io.emit('userList',names)
        console.log("没有重复");
        //登录成功
        //让socket对象记下当前用户名
        socket.username = data.username;
        console.log("c:"+socket.username);
        console.log("c:"+data.username);
        //给所有用户数组添加一个用户对象
        names.push(data);
        //注册messageALL事件用于所有浏览器广播
        socket.broadcast.emit('messageALL',{
          name:`${data.name} 饥渴难耐的上线了 ${time}]`,
          number:count
        });
        //触发事件:修改自己用户名为当前用户名
        socket.emit('changeMyName',data.name+'')
      }
      socket.on('newText',function(data){
        let text = data.text;
        socket.broadcast.emit('toMessage',{
          text:text,
          id:count,
          time:time,
          name:socket.username
        });
      });
      socket.on('getCOUNT',function(data){
        //监听客户端发的消息
      })
      socket.on('disconnect',function(data){
        count--;
        let index = names.findIndex(function(name){
          return name.username === socket.username;
        });
        console.log("当前数组为:"+names);
        names.splice(index,1);
        console.log("之后数组为:"+names);
        console.log(socket.username);
        socket.emit('userEXIT', {name:socket.username});
        console.log('User disconnected');
        socket.broadcast.emit('messageEXIT',{
          name:`${data.name} Ta丢下你们走了 [${time}]`,
          number:count
        });  
        console.log("失去一位连接");
    });
    })
    // io.on('disconnect',function(socket){
    //   socket.broadcast.emit('messageEXIT',{
    //     name:'第'+ count-- +'位用户退出聊天室 ' + '['+time+']',
    //     count:count
    //   });
    //   console.log("失去一位链接");
    // });
    // socket.emit('msg',{
    //   number: count
    // })
});
console.log("亲爱的李吉,4000端口开启");